package com.ccepc.algmanage.scheduled;

import com.alibaba.fastjson.JSON;
import com.ccepc.admin.api.dto.CreateMessageModel;
import com.ccepc.admin.api.feign.RemoteMessageService;
import com.ccepc.algmanage.service.AlgorithmInfoService;
import com.ccepc.algmanage.service.IdentificationRecordService;
import com.ccepc.algmanage.utils.AuthInfoUtils;
import com.ccepc.algmanage.utils.CommonUtils;
import com.ccepc.common.core.constant.SecurityConstants;
import com.ccepc.common.core.util.R;
import com.ccepc.common.security.service.PigxUser;
import com.ccepc.demo.api.entity.AlgorithmInfo;
import com.ccepc.demo.api.entity.IdentificationRecord;
import com.ccepc.demo.api.entity.PushRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;

@Slf4j
@Service
public class PushRuleJud {
    @Resource
    private RemoteMessageService remoteMessageService;
    @Resource
    private AlgorithmInfoService algorithmInfoService;
    @Resource
    private IdentificationRecordService identificationRecordService;
    private static final String BASE_URL = "https://121.36.40.162:443";

    void checkAlarm(IdentificationRecord identificationRecord, PushRule pushRule, String pushmanId) {
        if (pushRule.getAlarmLevel().contains(String.valueOf(identificationRecord.getEventLvl())) ||
                pushRule.getAlarmLevel().contains("3")){
            // 获取当前时间
            LocalTime currentTime = LocalTime.now();
            // 解析开始时间和结束时间
            LocalTime alarmStartTime = LocalTime.parse(pushRule.getStartTime());
            LocalTime alarmEndTime = LocalTime.parse(pushRule.getEndTime());
            // 是否在推送时间内
            if (isTimeInRange(currentTime, alarmStartTime, alarmEndTime)) {
                if (pushRule.getOnlyOnce() == 0) {
                    long pushIntervalInMinutes = convertToMinutes(pushRule.getPushInterval(), pushRule.getTimeUnit());
                    long timeDifference = ChronoUnit.MINUTES.between(alarmStartTime, currentTime);
                    // 判断差值是否是推送间隔的整数倍
                    if (timeDifference % pushIntervalInMinutes == 0) {
                        sendNow(pushmanId, identificationRecord, pushRule.getTenantId(), pushRule);
                    }
                } else {
                    sendNow(pushmanId, identificationRecord, pushRule.getTenantId(), pushRule);
                }
                log.info(pushRule.getRuleName(), "验证条件通过，开始发送信息");
                identificationRecord.setIsPush(1);
                identificationRecordService.updateById(identificationRecord);
            }
        }
    }

    // 判断当前时间是否在报警时间范围内
    private static boolean isTimeInRange(LocalTime currentTime, LocalTime startTime, LocalTime endTime) {
        return !currentTime.isBefore(startTime) && !currentTime.isAfter(endTime);
    }

    // 将推送间隔转换为分钟
    private static long convertToMinutes(int interval, String unit) {
        switch (unit.toUpperCase()) {
            case "MINUTE":
                return interval;
            case "HOUR":
                return interval * 60L;
            case "DAY":
                return (long) interval * 60 * 24;
            default:
                throw new IllegalArgumentException("Unsupported time unit: " + unit);
        }
    }
    public void sendNow(String pushManIds, IdentificationRecord identificationRecord, Integer tenantId, PushRule pushRule) {
        String pushTypes = pushRule.getPushType();
        String[] pushTypeList = pushTypes.split(",");
        for (String pushType : pushTypeList) {
            log.info("推送方式："+pushType);
            CreateMessageModel createMessageModel = new CreateMessageModel();
            AlgorithmInfo algorithmInfo = algorithmInfoService.getById(identificationRecord.getAlgorimId());
            createMessageModel.setTitle(algorithmInfo.getAlgName());
            createMessageModel.setContent("您好! 您的" + algorithmInfo.getAlgName() + "算法当前处于未处理状态，请及时处理!");
            createMessageModel.setSmsContent(JSON.toJSONString(Arrays.asList("算法管理平台项目",algorithmInfo.getAlgName()+"最新的识别记录","未处理状态")));
            createMessageModel.setPushType(pushType);
            createMessageModel.setMsgType("project");
            createMessageModel.setMsgImg(BASE_URL + identificationRecord.getIdenResults());
            createMessageModel.setProjectName("算法平台");
            createMessageModel.setSubsystemName("IIPI");
            createMessageModel.setSystemType("111");
            createMessageModel.setPushNow(2);
            createMessageModel.setPushTime(LocalDateTime.now());
            createMessageModel.setPushUser("");
            createMessageModel.setReceiveUserIds(CommonUtils.stringToLongArray(pushManIds));
            createMessageModel.setTenantId(tenantId);
            createMessageModel.setMsgTemplate("");
            createMessageModel.setSourceId(1L);//
            R<Boolean> save = remoteMessageService.save(createMessageModel, SecurityConstants.FROM_IN);
            if (save.getData()){
                log.info("信息发送成功！");
            }
        }
    }
}
